<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\SystemNotice;

class SystemNoticeService
{
    public static function send($userId, $title, $desc, $content)
    {
        SystemNotice::insert([
            'user_id' => $userId,
            'title' => $title,
            'desc' => $desc,
            'content' => $content,
            'created_time' => date('Y-m-d H:i:s')
        ]);
    }

    public static function sendTemplate($userId, $template)
    {
        self::send($userId, $template['title'], $template['desc'], $template['content']);
    }

    public static function list($page, $length = 10)
    {
        $offset = ($page - 1) * $length;

        $query = SystemNotice::select(['id', 'user_id', 'title', 'desc', 'content', 'is_read', 'read_time'])->where('user_id', get_user_id());

        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->get()->toArray();

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function detail($id)
    {
        self::markRead($id);
        return SystemNotice::where('id', $id)->where('user_id', get_user_id())->first();
    }

    public static function latestMessage()
    {
        return SystemNotice::where('user_id', get_user_id())->orderBy('created_time', 'desc')->first();
    }

    public static function uneadCount()
    {
        return SystemNotice::where('user_id', get_user_id())->where('is_read', 0)->count();
    }

    public static function markAllRead()
    {
        return SystemNotice::where('user_id', get_user_id())->update(['is_read' => 1, 'read_time' => date('Y-m-d H:i:s')]);
    }

    public static function markRead($id)
    {
        return SystemNotice::where('user_id', get_user_id())->where('id', $id)->update(['is_read' => 1, 'read_time' => date('Y-m-d H:i:s')]);
    }
}